const HtmlWebpackPlugin = require('html-webpack-plugin');
const { createSSRApp } = require('vue');
const { renderToString } = require('vue/server-renderer');

/**
 * vue语法解析
 */
class VueLoad {
  apply(compiler) {
    compiler.hooks.compilation.tap('VueLoad', (compilation) => {
      HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync('VueLoad', async (data, cb) => {
        // vue解析
        data.html = await renderToString(
          createSSRApp({
            data: () => ({
              filename: data.plugin.options.filename,
              data: data.plugin.options.data,
            }),
            template: data.html,
          }),
        );
        // 去掉多余注释信息
        data.html = deleteNote(data.html);
        cb(null, data);
      });
    });
  }
}

/**
 * 去掉多余注释信息
 * @param {String} html 字符串
 * @returns
 */
function deleteNote(html) {
  return html.replace(/<!-- prettier-ignore-start -->|<!-- prettier-ignore-end -->|<!---->|<!--\[-->|<!--\]-->/g, '');
}

module.exports = VueLoad;
